package com.hongkzh.www.recruit.service;

import com.hongkzh.www.adv.service.BaseService;
import com.hongkzh.www.conmon.*;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.List;

public class RecruitService extends BaseService {

    public Record choiceRecruit(String loginUid) {
        SqlPara sqlPara= Db.getSqlPara("recruit.choiceRecruit",loginUid);

        Record r= Db.findFirst(sqlPara);
        r.set("isEnterprise","0");
        if(StrKit.notBlank(r.getStr("coverImgSrc"))){
            r.set("isEnterprise","1");
        }
        r.set("isUserResume","0");
        if(StrKit.notBlank(r.getStr("userResumeId"))){
            r.set("isUserResume","1");
        }
        return r;
    }

    public Record getRecruitEnterpriseInfo(String loginUid) {
        SqlPara sqlPara= Db.getSqlPara("recruit.getRecruitEnterpriseInfo",loginUid);
        Record r= Db.findFirst(sqlPara);
        if(null==r){
            return null;
        }
        doImgPath(r);
        if(StrKit.notBlank(r.getStr("scale"))) {
        r.set("scaleName",RedisTool.hgetDict("hk_recruit_scale_"+r.getStr("scale")));
        }
       if(StrKit.notBlank(r.getStr("stage"))) {
        r.set("stageName",RedisTool.hgetDict("hk_recruit_stage_"+r.getStr("stage")));
          }
        if(StrKit.notBlank(r.getStr("areaId"))) {
            r.set("areaName", RedisTool.hgetDict("area_" + r.get("areaId")));
        }
        r.set("industryName","");
        if(StrKit.notBlank(r.getStr("industry"))) {
            String sexName= RedisTool.hgetRecruitIndustry( r.get("industry"));
            if(StrKit.notBlank(sexName)){
                r.set("industryName",sexName);
            }
        }
        return r;
    }


    public List<Record> getRecruitPosition(String loginUid) {
        SqlPara sqlPara= Db.getSqlPara("recruit.getRecruitPosition",loginUid);
        List<Record> list=Db.find(sqlPara);
        for (Record r:list
             ) {
            doCache(r);
        }
        return list;
    }

    public Record getRecruitPositionDetailInfo(String recruitId) {
        SqlPara sqlPara= Db.getSqlPara("recruit.getRecruitPositionDetailInfo",recruitId);
        Record r= Db.findFirst(sqlPara);
        r.set("areaName",RedisTool.hgetArea(r.get("areaId")));
        return r;

    }
    @Before(Tx.class)
    public void updateRecruitPositionDetailInfo(String recruitId, String title, String salary, String areaId, String experience, String education, String nature, String introduce, String category, String enterpriseId, String state) {
        SqlPara sqlPara=null;
        if(StrKit.isBlank(recruitId)){
            recruitId=IdGen.uuid();
            Kv cond=Kv.by("recruitId",recruitId).set("title",title).set("salary",salary).set("areaId",areaId).set("experience",experience).set("state",state)
                    .set("education",education) .set("nature",nature).set("introduce",introduce).set("category",category).set("enterpriseId",enterpriseId);
            sqlPara=Db.getSqlPara("recruit.saveRecruitPositionDetailInfo",cond);
        }
        else{
            Kv cond=Kv.by("recruitId",recruitId).set("title",title).set("salary",salary).set("areaId",areaId).set("experience",experience).set("state",state)
                    .set("education",education) .set("nature",nature).set("introduce",introduce).set("category",category).set("enterpriseId",enterpriseId);
            sqlPara=Db.getSqlPara("recruit.updateRecruitPositionDetailInfo",cond);

        }
        Db.update(sqlPara);
    }

    public Record getUserInfo(String loginUid) {
        Record r= Db.findFirst(Db.getSqlPara("recruit.getUserInfo",loginUid));
        doCache(r);
        doImgPath(r);
        return  r;
    }

    public List<Record> getUserEducational( String loginUid) {
        String resumeId=updateResume(loginUid);
        SqlPara sqlPara= Db.getSqlPara("recruit.getUserEducational",resumeId,loginUid);
        List<Record> list=Db.find(sqlPara);
        for (Record r:list
                ) {
            doCache(r);
        }
        return list;
    }

    public List<Record> getUserExperience( String loginUid) {
        String resumeId=updateResume(loginUid);
        SqlPara sqlPara= Db.getSqlPara("recruit.getUserExperience",resumeId,loginUid);
        List<Record> list=Db.find(sqlPara);
        for (Record r:list
                ) {
            doCache(r);
        }
        return list;

    }
   private void updateUserEnterpriserecRuited(String loginUid,String type){

        //修改用户企业信息
       SqlPara sqlPara = Db.getSqlPara("recruit.updateUserEnterpriserecRuited", type, loginUid);
        Db.update(sqlPara);
    }
    @Before(Tx.class)
    public Record updateUserPortrait(String portrait, String loginUid) {
        String resumeId=updateResume(loginUid);
        Db.update(Db.getSqlPara("recruit.updateUserPortrait",resumeId,portrait));
        Record r=new Record();
        r.set("portrait",portrait);
        doImgPath(r);
        updateUserEnterpriserecRuited(loginUid,"1");
        return r;
    }
    @Before(Tx.class)
    public void updateUserBaseInfo(String loginUid,  String name, String sex, String education, String workingLife, String birthday, String located, String mobile, String email) {
        String resumeId=updateResume(loginUid);
        Kv cond=Kv.by("resumeId",resumeId).set("name",name).set("sex",sex).set("education",education).set("workingLife",workingLife).set("birthday",birthday).set("located",located)
                .set("mobile",mobile).set("email",email).set("loginUid",loginUid);
        Db.update(Db.getSqlPara("recruit.updateUserBaseInfo",cond));
        updateUserEnterpriserecRuited(loginUid,"1");
    }
    private String updateResume(String loginUid){
        Record r= Db.findFirst(Db.getSqlPara("recruit.selectUserResume",loginUid));
        String resumeId=null;
        if(null!=r){
            resumeId= r.getStr("id");
        }
        if(StrKit.isBlank(resumeId)){
            resumeId=IdGen.uuid();
            Db.update(Db.getSqlPara("recruit.updateResume",loginUid,resumeId));
        }
        return resumeId;
    }
    public void updateUserContent(String loginUid, String content) {
        String  resumeId=updateResume(loginUid);
        Db.update(Db.getSqlPara("recruit.updateUserContent",resumeId,content));
        updateUserEnterpriserecRuited(loginUid,"1");
    }

    public void updateUserEducational(String educatioId, String graduate, String major, String education, String graduationTime,String enrolmentTime, String loginUid) {
        String  resumeId=updateResume(loginUid);
        SqlPara sqlPara=null;
        if(StrKit.isBlank(educatioId)){
            educatioId=IdGen.uuid();
            Kv cond=Kv.by("educatioId",educatioId).set("graduate",graduate).set("major",major).set("resumeId",resumeId).set("loginUid",loginUid)
                    .set("education",education).set("graduationTime",graduationTime).set("enrolmentTime",enrolmentTime).set("loginUid",loginUid);
            sqlPara=Db.getSqlPara("recruit.saveUserEducational",cond);
        }
        else{
            Kv cond=Kv.by("educatioId",educatioId).set("graduate",graduate).set("major",major)
                    .set("education",education).set("graduationTime",graduationTime).set("enrolmentTime",enrolmentTime).set("loginUid",loginUid);
            sqlPara=Db.getSqlPara("recruit.updateUserEducational",cond);

        }
        Db.update(sqlPara);
    }

    public void updateUserExperience(String experienceId, String corporateName, String job, String workContent, String entryDate, String loginUid, String outDate) {
        String  resumeId=updateResume(loginUid);
        SqlPara sqlPara=null;
        if(StrKit.isBlank(experienceId)){
            experienceId=IdGen.uuid();
            Kv cond=Kv.by("experienceId",experienceId).set("corporateName",corporateName).set("job",job).set("resumeId",resumeId).set("loginUid",loginUid)
                    .set("workContent",workContent).set("entryDate",entryDate).set("outDate",outDate);
            sqlPara=Db.getSqlPara("recruit.saveUserExperience",cond);
        }
        else{
            Kv cond=Kv.by("experienceId",experienceId).set("corporateName",corporateName).set("job",job)
                    .set("workContent",workContent).set("entryDate",entryDate).set("outDate",outDate);
            sqlPara=Db.getSqlPara("recruit.updateUserExperience",cond);

        }
        Db.update(sqlPara);
    }
    @Before(Tx.class)
    public Record updateAuthenticationEnterpriseInfo(String enterpriseId, String idCardImg, String businessLicenseImg, String headImg, String userName, String duties,
                                                     String hrEmail, String name, String abbreviation, String industry, String scale, String stage, String loginUid) {
        Record record=new Record();
        record.set("code",0);

        SqlPara sqlPara=null;

        Record r =choiceRecruit(loginUid);
        if(StrKit.isBlank(enterpriseId) ){
            if(!"0".equals(r.getStr("isEnterpriserecRuited"))) {
                record.set("message", "已经发布过");
                return record;
            }
        }
        else  {
            if(!enterpriseId.equals(r.getStr("userEnterpriseId"))) {
                record.set("message", "不是本人名下企业不能修改");
                return record;
            }
        }
        if(StrKit.isBlank(enterpriseId)){
            enterpriseId=IdGen.uuid();
            Kv cond=Kv.by("enterpriseId",enterpriseId).set("idCardImg",idCardImg).set("businessLicenseImg",businessLicenseImg)
                    .set("headImg",headImg).set("userName",userName).set("duties",duties)
                    .set("hrEmail",hrEmail).set("name",name).set("abbreviation",abbreviation)
                    .set("industry",industry).set("scale",scale).set("stage",stage).set("loginUid",loginUid);
            sqlPara=Db.getSqlPara("recruit.saveAuthenticationEnterpriseInfo",cond);
        }
        else{
            Kv cond=Kv.by("enterpriseId",enterpriseId).set("idCardImg",idCardImg).set("businessLicenseImg",businessLicenseImg)
                    .set("headImg",headImg).set("userName",userName).set("duties",duties)
                    .set("hrEmail",hrEmail).set("name",name).set("abbreviation",abbreviation)
                    .set("industry",industry).set("scale",scale).set("stage",stage).set("loginUid",loginUid);
            sqlPara=Db.getSqlPara("recruit.updateAuthenticationEnterpriseInfo",cond);

        }
        Db.update(sqlPara);
        if(!"2".equals(r.getStr("isEnterpriserecRuited"))) {
            updateUserEnterpriserecRuited(loginUid,"2");
        }

        return record;
    }
  @Before(Tx.class)
    public void updateEnterpriseInfo(String enterpriseId, String introduce, String areaId, String headImg, String address,
                                       String website, String mailbox, String scale, String stage, String loginUid) {
      SqlPara sqlPara=null;
        Kv cond=Kv.by("enterpriseId",enterpriseId).set("introduce",introduce).set("areaId",areaId)
              .set("headImg",headImg).set("address",address).set("website",website)
              .set("mailbox",mailbox).set("scale",scale).set("stage",stage).set("loginUid",loginUid);
      sqlPara=Db.getSqlPara("recruit.updateEnterpriseInfo",cond);
      Db.update(sqlPara);
  }
    @Before(Tx.class)
    public void updateCareerIntentions(String loginUid, String functions, String workNature, String salary,
                                       String place, String state, String timeToPost) {
        String resumeId=updateResume(loginUid);
        SqlPara sqlPara=null;
        Kv cond=Kv.by("functions",functions).set("workNature",workNature).set("salary",salary)
                .set("place",place).set("state",state).set("timeToPost",timeToPost) .set("resumeId",resumeId);
        sqlPara=Db.getSqlPara("recruit.updateCareerIntentions",cond);
        Db.update(sqlPara);
    }
    @Before(Tx.class)
    public void deleteUserExperience(String experienceId, String loginUid) {
        SqlPara sqlPara=Db.getSqlPara("recruit.deleteUserExperience",experienceId);
        Db.update(sqlPara);
    }
    @Before(Tx.class)
    public void deleteUserEducational(String educatioId, String loginUid) {
        SqlPara sqlPara=Db.getSqlPara("recruit.deleteUserEducational",educatioId);
        Db.update(sqlPara);
    }

    public Page<Record> getEnterpriseRecruitList(String categoryId, int pageNumber, String areaId, String salaryId, String title) {
         Kv cond=Kv.by("1=","1");
             cond.set("categoryId",categoryId);
            cond.set("areaId",areaId);
            cond.set("salaryId",salaryId);
            cond.set("title",title);
        SqlPara sqlPara=Db.getSqlPara("recruit.getEnterpriseRecruitList",cond);
            Page<Record> page= Db.paginate(pageNumber, StaticPublic.PAGESIZE,sqlPara);
            for (Record r:page.getList()
                 ) {
                doImgPath(r);
               doCache(r);

            }


        return page;
    }

    public Record recruitSearchHistory(String loginUid) {
        SqlPara sqlPara=Db.getSqlPara("recruit.hotsearch");
        List<Record> hots=Db.find(sqlPara);
        Record r=new Record();
        r.set("hosts",hots);
        sqlPara=Db.getSqlPara("recruit.searchHistory",loginUid);
        List<Record> historys=Db.find(sqlPara);
        r.set("historys",historys);
        return r;
    }
    @Before(Tx.class)
    public void deleteSearchHistory(String loginUid, String historyId) {
        Db.update(Db.getSqlPara("recruit.deleteSearchHistory",historyId));
    }

    public List<Record> searchRecruit(String loginUid, String name) {
        return Db.find(Db.getSqlPara("recruit.searchRecruit",name));
    }

    public Record getRecruitInfo(String loginUid, String recruitId) {
        Record r=Db.findFirst(Db.getSqlPara("recruit.getRecruitInfo",recruitId));
        doImgPath(r);
        doCache(r);
        if(StrKit.notBlank(r.getStr("areaId"))) {
            String sexName=  RedisTool.hgetArea( RedisTool.hget("area:"+r.get("areaId"),"parentId") );
            r.set("cityAreaName","");
            if(StrKit.notBlank(sexName)){
                r.set("cityAreaName",sexName+"-"+RedisTool.hgetArea(r.get("areaId")));
            }
        }

        return r;
    }

    public Record getEnterpriseRecruitListById(String loginUid, String enterpriseId) {
        SqlPara sqlPara=Db.getSqlPara("recruit.getEnterpriseRecruitListById",enterpriseId);
        Record r=Db.findFirst(sqlPara);
        doImgPath(r);
        doCache(r);
        r.set("scaleName","");
        if(StrKit.notBlank(r.getStr("scale"))) {
            r.set("scaleName",RedisTool.hgetDict("hk_recruit_scale_"+r.getStr("scale")));
        }
        r.set("stageName","");
        if(StrKit.notBlank(r.getStr("stage"))) {
            r.set("stageName",RedisTool.hgetDict("hk_recruit_stage_"+r.getStr("stage")));
        }

        sqlPara=Db.getSqlPara("recruit.getRecruitByEnterpriseId",enterpriseId);
        List<Record>list=Db.find(sqlPara);
        for (Record recruit:list
             ) {
            doCache(recruit);
            recruit.set("createDate",DateUtil.FormatDate2(recruit.getDate("createDate")));
        }
        r.set("recruits",list);
        return r;
    }
    @Before(Tx.class)
    public void updateUserData(String loginUid, String nickname, String sex, String education,
                               String constellation, String birthday, String height,
                               String monthlyIncome, String weight, String located,
                               String marital, String hobby, String occupation,String age) {

               /* Kv cond=Kv.by("nickname=",nickname);
                if(StrKit.notBlank(sex)) {
                    cond.set("sex=", sex);
                }
                if(StrKit.notBlank(age)) {
                    cond.set("age=", age);
                }
                cond.set("education=",education)
                .set("constellation=",constellation).
                 set("birthday=",birthday).set("located=",located)
                .set("height=",height).set("monthlyIncome=",monthlyIncome).set("weight=",weight)
                .set("marital=",marital).set("hobby=",hobby).set("occupation=",occupation);*/
        Kv cond=Kv.by("nickname",nickname).set("sex", sex).set("age", age) .set("education",education)
                .set("constellation",constellation).
                set("birthday",birthday).set("located",located)
                .set("height",height).set("monthlyIncome",monthlyIncome).set("weight",weight)
                .set("marital",marital).set("hobby",hobby).set("occupation",occupation).set("uid",loginUid);
        Db.update(Db.getSqlPara("user.updateUserData",cond));


    }
    @Before(Tx.class)
    public void saveSearch(String loginUid, String title) {
        Record record=Db.findFirst(Db.getSqlPara("recruit.searchHistoryBuName",loginUid,title));
       if(record==null) {
           Db.update(Db.getSqlPara("recruit.saveSearch",IdGen.uuid(), loginUid, title));
           Db.update(Db.getSqlPara("recruit.savehotSearch",IdGen.uuid(), loginUid, title));

       }else {
           Db.update(Db.getSqlPara("recruit.updateSearch",loginUid,title));
           Db.update(Db.getSqlPara("recruit.updatehotSearch",title));
       }
    }

    public List<Record> getShieldCompany(String loginUid) {
        return Db.find(Db.getSqlPara("recruit.getShieldCompany",loginUid));
    }
   @Before(Tx.class)
    public void deleteShieldCompany(String loginUid, String companyId) {
        Db.update(Db.getSqlPara("recruit.deleteShieldCompany",companyId,loginUid));
    }
    @Before(Tx.class)
    public void addShieldCompany(String loginUid, String corporateName) {
        Db.update(Db.getSqlPara("recruit.addShieldCompany",IdGen.uuid(),corporateName,loginUid));
    }
    @Before(Tx.class)
    public void deliveryRecruitInfo(String loginUid, String recruitId, String enterpriseId) {
        Record ru=Db.findFirst(Db.getSqlPara("recruit.selectResumeByUserid",loginUid));
            if(ru==null||StrKit.isBlank(ru.getStr("id"))){
                throw new BusinessException("没有简历");
            }
           String date=DateUtil.reduceDate(-30);

          Record r=Db.findFirst(Db.getSqlPara("recruit.selectDeliveryRecruitInfo",loginUid,recruitId,date));
          if(r!=null){
              throw new BusinessException("30天内请勿重复投递");
          }


          String id=IdGen.uuid();
          Db.update(Db.getSqlPara("recruit.saveDeliveryRecruitInfo",id,loginUid,ru.getStr("id"),recruitId,1,enterpriseId));
          Db.update(Db.getSqlPara("recruit.saveDeliveryRecruitInfoLog",IdGen.uuid(),id,"你的简历投递成功"));

    }

    public Record getUserRelationship(String loginUid, String uid) {
        Record re=new Record();
        String type="0";
        String key = String.format(StaticPublic.USERRELATIONSHIP, loginUid,uid);
        if (RedisTool.exists(key)) {
             type= (String) RedisTool.getObject(key);
            re.set("type",type);
            return re;
        }
        SqlPara sql=Db.getSqlPara("user.getfriend",loginUid,uid);
        Record r=Db.findFirst(sql);
        if(r!=null)
        {
            type="1";
        }
        else {
            sql = Db.getSqlPara("user.getfollow", loginUid, uid);
            r = Db.findFirst(sql);
            if (r != null) {
                type="2";
            }
        }
        re.set("type", type);
        RedisTool.setObject(key,type);
        return re;
    }
    @Before(Tx.class)
    public void emptySearchHistory(String loginUid) {
        Db.update(Db.getSqlPara("recruit.emptySearchHistory",loginUid));
    }

}
